#include "NewtonInterpolation.h"
#include <matplotlibcpp.h>
#include <cmath>
#include <algorithm>
using namespace std;
class GivenFunction {
public:
    // 定义函数 f(x) = 1 / (1 + x^2)
    double operator()(double x) const {
        return 1.0 / (1.0 + x * x);
    }
};
namespace plt = matplotlibcpp;

int main() {
    const int num_points[] = {2, 4, 6, 8}; // n值
    double x_min = -5, x_max = 5, step = 0.01;
    vector<double> x_fine;
    for (double x = x_min; x <= x_max; x += step) {
        x_fine.push_back(x);
    }
    vector<double> y_true, y_interpolated;

    for (int n : num_points) {
        vector<double> x_values, y_values;

        // 生成插值节点
        for (int i = 0; i <= n; ++i) {
            double x = x_min + (x_max - x_min) * i / n;
            x_values.push_back(x);
            y_values.push_back(GivenFunction()(x));
        }

        y_interpolated.clear();
        for (double x : x_fine) {
            y_interpolated.push_back(newtonInterpolation(x_values, y_values, x));
        }

        // 绘制精确函数和插值多项式
        vector<double> y_true;
        for (double x : x_fine) {
            y_true.push_back(GivenFunction()(x));
        }
        
        plt::figure();
        plt::named_plot("True Function", x_fine, y_true, "b");
        plt::named_plot("Interpolated Polynomial " + to_string(n), x_fine, y_interpolated, "r--");
        plt::legend();
        plt::show();
    }

    return 0;
}